package com.daohang361.imqq.pugin.decoder;

import java.io.File;
import java.util.HashMap;
import java.util.Set;

import org.apache.mina.core.session.IoSession;

import com.daohang361.imqq.Asycore.Connector;
import com.daohang361.imqq.Asycore.QQUser;
import com.daohang361.imqq.ServerContex.SessionContex;
import com.daohang361.imqq.decoder.InterfaceDecoder;
import com.daohang361.imqq.hotLoader.PuginManager;
import com.daohang361.imqq.service.InterfaceService;
import com.daohang361.imqq.tool.Hex2Bytes;
import com.daohang361.imqq.tool.MyByteReciveArray;

/** 
 * @author naner E-mail:likun3344@163.com 
 * @create time：2011-6-22 下午07:44:02 
 */
public class Decoder0125 implements InterfaceDecoder{
	
	public MyByteReciveArray myArray;
	public QQUser sessionQQ;
	public byte[] decryptAll=null;
	@Override
	public void init(MyByteReciveArray myArray, QQUser sessionQQ) {
		this.myArray=myArray;
		this.sessionQQ=sessionQQ;
	}
	@Override
	public QQUser decode() throws Exception {
		System.out.println("I'M Pugin Decoder0126");
		myArray.decryptRemain(sessionQQ.getAttr("SessionKey"));
		
		String command = Hex2Bytes.bytesToHexString(myArray.extract(0, 3));//子命令
		if(command.replace(" ", "").equals("00020100"))
		{
			System.out.println("decoder 01 26 :子命令00 02 01 00");
			HashMap<Integer,byte[]> qqheads = new HashMap<Integer,byte[]>(); 
			myArray.extract(0, 3);
			int length=myArray.extractInt(0, 0)-1;//长度
			int qq = myArray.extractInt(0, 3);
			myArray.extract(0, 3);
			byte[] X_FILEHASH =myArray.extract(0, 15);
			qqheads.put(qq,X_FILEHASH );
			while(length>0)
			{
				myArray.extract(0, 4);
				qq = myArray.extractInt(0, 3);
				myArray.extract(0, 3);
				X_FILEHASH =myArray.extract(0, 15);
				qqheads.put(qq,X_FILEHASH );
				length--;
			}
			myArray.extract(0, 6);
			byte[] X_SIGNSTRING=myArray.extract(0, 23);
			String basePath=SessionContex.getQQMainPath()+"\\users\\"+sessionQQ.getQq()+"\\userhead";
			String path=basePath+"\\check.db";
			System.out.println("path:"+path);
			 File file = new File(path);
			 File parent = file.getParentFile();   
			 if(parent.exists() == false) {   
				 parent.mkdirs();   
				 System.out.println("users dir not exists.But have created." ); 
			 }
			 Set<Integer> key =qqheads.keySet();
			 for(Integer i:key){
				 InterfaceService s=(InterfaceService) PuginManager.GetPuginByKey("GetFriendheadHttpClient");	
				 s.doService(
						 sessionQQ.getQq(),
						 i,
						 Hex2Bytes.bytesToHexString(qqheads.get(i)),
						 Hex2Bytes.bytesToHexString(X_SIGNSTRING),
						 basePath+"\\"+i+".gif");
			 }
			 
		}
	
		 
		Connector connector =SessionContex.getConnector(sessionQQ.getQq());
		IoSession Mainsession=connector.getSession();
		Mainsession.write(sessionQQ);
		sessionQQ.setCommand(0);
		return sessionQQ;
	}

	@Override
	public Object invoke(Object... o) {
		// TODO Auto-generated method stub
		return null;
	}

}
